local skynet = require "skynet"
local mysql = require "mysql"
local snax = require "snax"
local cluster = require "cluster"
local CMD = require "center_proto"
local httpc = require "http.httpc"
local db = require "dblib"

--[[
豆花代理系统
]]

local DOUHUA = {}

local SMSConfig = {
    appid = '16104',
    signature = '84cce091bd93681b033339f730b6a12d',
    --content = '【麟云科技有限公司】您的验证码是：%s(5分钟内有效)',
    --content = '【豆花麻将】验证码:%s（豆花麻将申请代理手机验证码，5分钟内有效,请勿透露给其他人）',
    --content = '【豆花麻将】恭喜您成为金牌代理! 代理账号：13888888888 密码：123456。 %s钻石已冲入您的代理账号，请尽快进入代理后台修改密码! 微信公众号：laoyougongzhong',
    host = 'api.mysubmail.com',
    url = '/message/send'
}

local VerifyCode = {}

-- 产生验证码
function DOUHUA.GenerateVerifyCode()
    return ''..math.random(1000, 9999)
end

function DOUHUA.test_sms( ... )
    local form = SMSConfig
    form.to = ''..13714491123
    local verifyCode = DOUHUA.GenerateVerifyCode()
    
    form.content = string.format(form.content, verifyCode)
    local status, body =  httpc.post(form.host, form.url, form, recvheader)
    local postRet = string.find(body, "\"status\":\"success\"")
end

function DOUHUA.NotifyUserSMS( account,diamond,agentlv )
    local form = SMSConfig
    strp = {}
    
    strp[1] = "金"
    strp[2] = "银"
    strp[3] = "铜"

    form.to = ''..account
    form.content = '【豆花麻将】恭喜您成为%s牌代理! 代理账号：%s 密码：123456。 %s钻石已冲入您的代理账号，请尽快进入代理后台修改密码! 微信公众号：laoyougongzhong'
    form.content = string.format(form.content, strp[agentlv],account,diamond)
    local status, body =  httpc.post(form.host, form.url, form, recvheader)
    local postRet = string.find(body, "\"status\":\"success\"")
end

--查询用户代理的情况
function DOUHUA.UserAgentQuery(playid)
    skynet.error('[DOUHUA.UserAgentQuery] playid=',playid)

    local res1, res2 = db.call("call Pr_AGS_check_user_status("..tonumber(playid)..",@intLevel,@intDiamondCount,@intIsAgent);","select @intLevel,@intDiamondCount,@intIsAgent")

    local result = res2[1]['@intIsAgent']
    local lv     = res2[1]['@intLevel']
	local dia    = res2[1]['@intDiamondCount']
	
	skynet.error("db get result=",result," lv=",lv," dia=",dia)
	
	local re = {mcmd = CMD.Main_Douhua_module,scmd = CMD.Sub_Douhua_UserAgentStatus, msg = string.pack('<BI4I4', result, lv, dia)} 
    --local re = {mcmd = CMD.Main_Douhua_module,scmd = CMD.Sub_Douhua_UserAgentStatus, msg = string.pack('b', temp[bSuc])} 
    return re    
end

--检测手机是否可用
function DOUHUA.CheckPhoneNumberReq( playid,msg )
    skynet.error('[DOUHUA.CheckPhoneNumberReq]]')
    
    local phoneNum = string.unpack("<c11",msg,1)
    skynet.error(" phoneNum=",phoneNum)
    
    local res1, res2 = db.call("call Pr_AGS_check_phone_number(\'"..phoneNum.."\',@rVal);","select @rVal")
    local result = res2[1]['@rVal']

    skynet.error("db get result=",result)

    local re = {mcmd = CMD.Main_Douhua_module,scmd = CMD.Sub_Douhua_CheckPhoneNumberResp, msg = string.pack('b', result)} 
    return re    
end

--用户请求手机验证码
function DOUHUA.MPVcodeReq(playid,msg)
    
	local pid,phoneNum = string.unpack("<I4c64", msg, 1)
    phoneNum = string.sub(phoneNum,1,11)
	skynet.error("[DOUHUA.MPVcodeReq] phoneNum=",phoneNum," pid=",pid)
	
    local recvheader = {}
    local form = SMSConfig
    form.to = ''..phoneNum
    local verifyCode = DOUHUA.GenerateVerifyCode()
    form.content = '【豆花麻将】验证码:%s（豆花麻将申请代理手机验证码，5分钟内有效,请勿透露给其他人）'
    form.content = string.format(form.content, verifyCode)
    local status, body =  httpc.post(form.host, form.url, form, recvheader)
    local postRet = string.find(body, "\"status\":\"success\"")

    local bSuc = true
    if not postRet then bSuc = false 
    else 
		VerifyCode[phoneNum] = {t = os.time(), code = tonumber(verifyCode)}
    end
    
    skynet.error('DOUHUA Phone SMS http request', 'phone=', phoneNum)
    
    -- 不需要返回客户端
    -- local re = {mcmd = CMD.Main_Douhua_module,scmd = CMD.Sub_Douhua_MPVcodeResp, msg = string.pack('b', temp[bSuc])} 
    -- return re    
end

--用户提交资料
function DOUHUA.SubmitInfoReq( playid,msg )
    skynet.error('[DOUHUA.SubmitInfoReq]]')

    local pid,cname,phoneNum,phoneVCode = string.unpack("<I4c128c64I4",msg,1)
    phoneNum = string.sub(phoneNum,1,11)

    skynet.error("cname="..cname)
    skynet.error("phoneNum="..phoneNum)
    skynet.error("phoneVCode="..phoneVCode)

    local user_name = string.sub(cname,1,80)

    local ret = 0
    local result = 10   --  1 - 正确  10 - 手机信息不正确  20 - 姓名不正确

    -- 对验证码进行核对

    if VerifyCode[phoneNum] then 
        
        skynet.error("in vcode...",VerifyCode[phoneNum].code)

        if VerifyCode[phoneNum].code ~= phoneVCode then 
                ret = 3    --验证码不匹配
        else
            if (VerifyCode[phoneNum].t - os.time() < 60 * 5) then 
                ret = 1    --成功
            else 
                ret = 2    --超时
            end
        end
    else
        ret = 4  -- 没有找到这个手机的记录
    end

    skynet.error("VerifyCode ret =",ret)

    if ret~=1 then
        local re = {mcmd = CMD.Main_Douhua_module,scmd = CMD.Sub_Douhua_SubmitInfoResp, msg = string.pack('B', result)} 
        return re    
    end

    local res1, res2 = db.call("call Pro_AddEnterPrise2(\'"..phoneNum.."\',\'"..user_name.."\',"..playid..",@return);","select @return")

    local result = res2[1]['@return']
    skynet.error("db get result=",result)

    local re = {mcmd = CMD.Main_Douhua_module,scmd = CMD.Sub_Douhua_SubmitInfoResp, msg = string.pack('B', result)} 
    return re    
end

--用户查询充值后的结果
function DOUHUA.CheckRecharge(playid, msg)
    skynet.error('[DOUHUA.CheckRecharge]]')
	local pid,flag = string.unpack("<I4I4", msg, 1)
	skynet.error("playid= ", pid, "flag= ", flag)

    local result,account,password,agentlv,diamon

    local res1, res2 = db.call("call Pr_AGS_user_recharge_done("..playid..","..flag..",@strAccount,@intDiamond,@intLevel,@rVal);","select @strAccount,@intDiamond,@intLevel,@rVal")
    local re = nil
    
    account = res2[1]['@strAccount']
    diamon  = res2[1]['@intDiamond']
    agentlv = res2[1]['@intLevel']
    result  = res2[1]['@rVal']

    skynet.error("db get result=",result)

    if result~=1 then
        return re
    end

    skynet.error("account="..account)
    skynet.error("diamon="..diamon)
    skynet.error("agentlv="..agentlv)

	--注册充值  (返回注册是否成功，账号，密码，级别)
	if flag == 1 then
		re = {mcmd = CMD.Main_Douhua_module,scmd = CMD.Sub_Douhua_RegDone, msg = string.pack('Bc64c64I4', result, account,"123456", agentlv)} 
        DOUHUA.NotifyUserSMS(account,diamon,agentlv)
        skynet.error("发送注册充值后的结果")
	end

	--购买充值(可能导致升级,返回级别和钻石数)
	if flag == 2 then
		re = {mcmd = CMD.Main_Douhua_module,scmd = CMD.Sub_Douhua_RechargeResp, msg = string.pack('I4I4', agentlv, diamon)} 
        skynet.error("发送充值后的结果")
    end

    return re
end


function response.request_douhua_system(conf)   --{cmd,playid,msg}
    
    skynet.error("[request_douhua_system] request_msg ",conf.playid,conf.cmd,conf.msg)

    if conf.cmd == CMD.Sub_Douhua_UserAgentQuery then               --查询用户代理的情况
        return DOUHUA.UserAgentQuery(conf.playid)
        
    elseif conf.cmd == CMD.Sub_Douhua_CheckPhoneNumberReq then      --检测手机是否可用
        return DOUHUA.CheckPhoneNumberReq(conf.playid, conf.msg)
            
    elseif conf.cmd == CMD.Sub_Douhua_MPVcodeReq then               --用户请求手机验证码
        return DOUHUA.MPVcodeReq(conf.playid, conf.msg)

    elseif conf.cmd == CMD.Sub_Douhua_SubmitInfoReq then            --用户提交资料
        return DOUHUA.SubmitInfoReq(conf.playid, conf.msg)

    elseif conf.cmd == CMD.Sub_Douhua_CheckRecharge then            --用户查询充值后的结果
        return DOUHUA.CheckRecharge(conf.playid, conf.msg)

    end 
end


function init( ... )
    skynet.error("douhua_agent_system server start:")
    snax.enablecluster()
    --DOUHUA.test_sms()
end


function exit(...)
    skynet.error ("douhua_agent_system server exit:", ...)
end